package com.learn.concurrent.itcast.thread.interaction.example1;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 线程的等待通知机制
 */
public class WaitAndNotify {
    private static boolean flag = true;
    private static Object lock = new Object();
    private static Object lock2 = new Object();


    public static void main(String[] args) {

        /*try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        Thread waitThread = new Thread(new Wait(), "WaitThread");
        waitThread.start();

        Thread notifyThread = new Thread(new Notify(), "NotifyThread");
        notifyThread.start();


    }

    private static class Wait implements Runnable {
        @Override
        public void run() {
            synchronized (lock) {
                while (flag) {
                    System.out.println(Thread.currentThread() + " flag是true,wait。。" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread() + " flag是false，开始继续工作" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                }
            }
        }
    }

    private static class Notify implements Runnable{
        @Override
        public void run() {
            synchronized (lock){
                System.out.println(Thread.currentThread() + " 持有锁，发出通知" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                lock.notifyAll();
                flag = false;
                try {
                    TimeUnit.SECONDS.sleep(15);
                    System.out.println(Thread.currentThread()+" 持有锁执行完毕");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 再次加锁
                synchronized (lock) {
                    System.out.println(Thread.currentThread() + " 再次拿到锁. sleep @ " + new SimpleDateFormat("HH:mm:ss").format(new Date()));
                    try {
                        TimeUnit.SECONDS.sleep(5);
                        System.out.println(Thread.currentThread()+" 持有锁再次执行完毕");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
